package com.evaluation.kexingcp.psycho.evaluation.sys.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.evaluation.kexingcp.admin.api.dto.UserDTO;
import com.evaluation.kexingcp.admin.api.entity.SysTenant;
import com.evaluation.kexingcp.admin.api.vo.UserExcelVO;
import com.evaluation.kexingcp.common.core.util.R;
import com.evaluation.kexingcp.common.excel.annotation.ResponseExcel;
import com.evaluation.kexingcp.common.log.annotation.SysLog;
import com.evaluation.kexingcp.common.security.util.SecurityUtils;
import com.evaluation.kexingcp.psycho.evaluation.sys.entity.EvaluationGeneralResultEntity;
import com.evaluation.kexingcp.psycho.evaluation.sys.service.EvaluationGeneralResultService;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 普查结果表
 *
 * @author kexingcp
 * @date 2024-11-20 10:10:33
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/evaluationGeneralResult" )
@Tag(description = "evaluationGeneralResult" , name = "普查结果表管理" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class EvaluationGeneralResultController {

    private final EvaluationGeneralResultService evaluationGeneralResultService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param evaluationGeneralResult 普查结果表
     * @return
     */
    @Operation(summary = "分页查询" , description = "分页查询" )
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('admin_evaluationGeneralResult_view')" )
    public R getEvaluationGeneralResultPage(@ParameterObject Page page, @ParameterObject EvaluationGeneralResultEntity evaluationGeneralResult) {
        LambdaQueryWrapper<EvaluationGeneralResultEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Objects.nonNull(evaluationGeneralResult.getTaskId()), EvaluationGeneralResultEntity::getTaskId, evaluationGeneralResult.getTaskId());
        wrapper.like(Objects.nonNull(evaluationGeneralResult.getUsername()), EvaluationGeneralResultEntity::getUsername, evaluationGeneralResult.getUsername());
        return R.ok(evaluationGeneralResultService.page(page, wrapper));
    }


    /**
     * 通过id查询普查结果表
     * @param id id
     * @return R
     */
    @Operation(summary = "通过id查询" , description = "通过id查询" )
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('admin_evaluationGeneralResult_view')" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(evaluationGeneralResultService.getById(id));
    }

    /**
     * 新增普查结果表
     * @param evaluationGeneralResult 普查结果表
     * @return R
     */
    @Operation(summary = "新增普查结果表" , description = "新增普查结果表" )
    @SysLog("新增普查结果表" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('admin_evaluationGeneralResult_add')" )
    public R save(@RequestBody EvaluationGeneralResultEntity evaluationGeneralResult) {
        return R.ok(evaluationGeneralResultService.save(evaluationGeneralResult));
    }

    /**
     * 修改普查结果表
     * @param evaluationGeneralResult 普查结果表
     * @return R
     */
    @Operation(summary = "修改普查结果表" , description = "修改普查结果表" )
    @SysLog("修改普查结果表" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('admin_evaluationGeneralResult_edit')" )
    public R updateById(@RequestBody EvaluationGeneralResultEntity evaluationGeneralResult) {
        return R.ok(evaluationGeneralResultService.updateById(evaluationGeneralResult));
    }

    /**
     * 通过id删除普查结果表
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除普查结果表" , description = "通过id删除普查结果表" )
    @SysLog("通过id删除普查结果表" )
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('admin_evaluationGeneralResult_del')" )
    public R removeById(@RequestBody Long[] ids) {
        return R.ok(evaluationGeneralResultService.removeBatchByIds(CollUtil.toList(ids)));
    }


    /**
     * 导出excel 表格
     */
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('admin_evaluationGeneralResult_export')" )
    public void userExport(HttpServletResponse response, @RequestParam(value = "taskId", required = false) Long taskId) throws IOException {
        List<String> title = new ArrayList<>(List.of("姓名","性别", "年龄", "学历", "职业", "电话", "测评结果"));

        XSSFWorkbook workbook = new XSSFWorkbook();
        //创建工作表sheet
        XSSFSheet sheet = workbook.createSheet();
        //创建第一行
        XSSFRow row = sheet.createRow(0);
        row.setHeightInPoints(30);

        XSSFCell cell = null;
        //插入第一行的表头
        for (int i = 0; i < title.size(); i++) {
            cell = row.createCell(i);
            cell.setCellValue(title.get(i));

            XSSFCellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
            cellStyle.setBorderLeft(BorderStyle.THIN);//左边框
            cellStyle.setBorderTop(BorderStyle.THIN);//上边框
            cellStyle.setBorderRight(BorderStyle.THIN);//右边框
            cellStyle.setFillBackgroundColor(IndexedColors.GREY_25_PERCENT.index);
            cellStyle.setWrapText(true);
            XSSFFont font =workbook.createFont();
            font.setBold(true);
            cellStyle.setFont(font);
            cell.setCellStyle(cellStyle);
            sheet.setColumnWidth(i, 10 * 256);
        }

        List<EvaluationGeneralResultEntity> data;
        if (taskId == null) {
            data = evaluationGeneralResultService.list();
        } else {
            data = evaluationGeneralResultService.list(Wrappers.lambdaQuery(EvaluationGeneralResultEntity.class).eq(EvaluationGeneralResultEntity::getTaskId, taskId));
        }

        // 写入数据
        for (int i = 0; i < data.size(); i++) {
            row = sheet.createRow(i + 1);
            for (String t : title) {
                int j = ListUtils.indexOf(title, s -> StringUtils.equalsIgnoreCase(t, s));
                cell = row.createCell(j);
                // "姓名","性别", "年龄", "学历", "电话", "测评结果"
                if (StringUtils.equalsIgnoreCase(t, "姓名")) {
                    cell.setCellValue(data.get(i).getUsername());
                } else if (StringUtils.equalsIgnoreCase(t, "性别")) {
                    cell.setCellValue(data.get(i).getSex());
                } else if (StringUtils.equalsIgnoreCase(t, "年龄")) {
                    cell.setCellValue(data.get(i).getAge());
                } else if (StringUtils.equalsIgnoreCase(t, "学历")) {
                    cell.setCellValue(data.get(i).getEdu());
                } else if (StringUtils.equalsIgnoreCase(t, "职业")) {
                    cell.setCellValue(data.get(i).getWork());
                } else if (StringUtils.equalsIgnoreCase(t, "电话")) {
                    cell.setCellValue(data.get(i).getMobile());
                } else if (StringUtils.equalsIgnoreCase(t, "测评结果")) {
                    String result = data.get(i).getFactorResult();
                    if (StrUtil.isNotBlank(result)) {
                        try {
                            JSONArray jsonArray = JSON.parseArray(result);
                            StringBuilder sb = new StringBuilder();
                            for (int k = 0; k < jsonArray.size(); k++) {
                                JSONObject jsonObject = jsonArray.getJSONObject(k);
                                sb.append(jsonObject.getString("factorName")).append(":").append(jsonObject.getString("result")).append(";");
                            }
                            cell.setCellValue(sb.toString());
                        } catch (Exception e) {
                            cell.setCellValue(result);
                        }
                    } else {
                        cell.setCellValue("");
                    }
                } else {
                    cell.setCellValue("");
                }
            }
        }

        workbook.write(response.getOutputStream());
    }
}